package com.xbongbong.paas.help;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.function.Consumer;

/**
 *事务帮助类
 *
 *@author weijianxun
 *@date 2022/10/21 12:44
 */
@Service("transactionHelp")
public class TransactionHelp {

    private final Logger LOG = LoggerFactory.getLogger(TransactionHelp.class);

    /**
     * 如果当前存在事务则事务提交成功后执行，反之直接执行
     * @param consumer
     */
    public void afterCommitOrCommitNow(Consumer consumer) {
        try {
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                    @Override
                    public void afterCommit() {
                        consumer.accept(null);
                    }
                });
            } else {
                consumer.accept(null);
            }
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.help.transaction.TransactionHelp.afterCommitOrCommitNow", e);
        }
    }
}
